package mysql

import (
	"gorm.io/gorm"
)

type OrderLx struct {
	gorm.Model
	UserId     int64   `gorm:"type:int(10);index;not null;comment:用户id;"`
	GoodsTitle string  `gorm:"type:varchar(50);index;not null;comment:用户id;"`
	GoodsSn    string  `gorm:"type:varchar(30);default:0;comment:订单编号;"`
	Amount     float32 `gorm:"type:decimal(10,2);index;default:0;comment:总金额;"`
	Payment    int8    `gorm:"type:tinyint(1);default:1; comment:支付方式 1代表支付宝 0代表微信 3代表银联;"`
	Status     int8    `gorm:"type:tinyint(1);index;not null;comment:订单状态 1代表上架 0 代表下架;"`
}

// 创建订单
func (o *OrderLx) CreateOrder() error {
	return DB.Create(&o).Error
}

// 订单详情
func (o *OrderLx) OrderDetail(userid, orderId int) error {
	return DB.Where("id = ?", orderId).Where("user_id", userid).First(&o).Error
}

// 订单列表
func (o *OrderLx) OrderList(keyword string, page, pageSize int) (list []*OrderLx, err error) {
	err = DB.Where("goods_title = ?", keyword).Scopes(Paginate(page, pageSize)).Find(&list).Error
	return list, err
}

// 分页
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}
		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
